import sys
import os
grandparent_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(grandparent_dir)

import folium
from folium import plugins
from folium.plugins import AntPath
import pickle
from utils.tools import read_json

def generate_map(coordinates_list, names, destination_name, style, map_output_path, positions, fitness, d, t, datas, name_style, data1, data2):
    colors = ['darkgreen', 'red', 'darkred', 'blue', 'purple', 'darkblue', 'green']
    #random.shuffle(colors)
    colors = colors[:len(names)]

    # 创建地图对象（自动适配坐标范围）
    m = folium.Map(location=coordinates_list[0][-1], zoom_start=5)
    m_new = folium.Map(location=coordinates_list[0][-1], zoom_start=5)
    ii = 0
    # 添加路径节点标记   
    for coordinates, name, color in zip(coordinates_list, names, colors):

        # 创建单独的地图对象（自动适配坐标范围）
        m_one = folium.Map(location=coordinates_list[0][-1], zoom_start=5)

        # 绘制路径（支持多种样式）
        # 基础路径
        folium.PolyLine(
            locations=coordinates,
            color=color,        
            weight=5,               # 线宽
            opacity=0.8,            # 透明度
            popup=name
        ).add_to(m)
        AntPath(
            locations=data1[0][4][ii],
            color="red",
            weight=5,
            dash_array=[10, 20],  # 虚线样式
            delay=1000,           # 动画延迟时间（毫秒）
            pulse_color='white'   # 箭头闪烁颜色
        ).add_to(m_new)
        AntPath(
            locations=data1[1][4][ii],
            color="blue",
            weight=5,
            dash_array=[10, 20],  # 虚线样式
            delay=1000,           # 动画延迟时间（毫秒）
            pulse_color='white'   # 箭头闪烁颜色
        ).add_to(m_new)        

        folium.PolyLine(
            locations=coordinates,
            color=color,        
            weight=5,               # 线宽
            opacity=0.8,            # 透明度
            popup=name
        ).add_to(m_one)  

        folium.Marker(
            location=[coordinates[0][0], coordinates[0][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color=color,   
                fill=True,
                fill_opacity=0.7,
                html='<div style="font-size: 20px; color: %s;">%s</div>' %(color, name),
            )
        ).add_to(m)
        folium.Marker(
            location=[coordinates[0][0], coordinates[0][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color=color,   
                fill=True,
                fill_opacity=0.7,
                html='<div style="font-size: 20px; color: %s;">%s</div>' %(color, name),
            )
        ).add_to(m_new)        
        text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                %s<br>%s<br>%s<br>物资提供量:%s<br>达到所需时间:%d秒<br>距离:%.2f公里
            </div>
        '''%(color, name[:5], name[5:11], name[11:], "["+",".join(list(map(str, positions[ii].tolist())))+"]", int(t[ii]), float(datas[ii][0]))
        folium.map.Marker(
            [coordinates[0][0]+0.01, coordinates[0][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m)     
        text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                最快路线:<br>%s<br>%d秒<br>%.2f公里
            </div>
        '''%("red", "["+",".join(list(map(str, data2[0][0][ii].tolist())))+"]", int(data2[0][2][ii]), float(data1[0][5][ii][0]))
        folium.map.Marker(
            [coordinates[0][0]+0.01, coordinates[0][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_new)
        text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                <br><br><br><br>最短路线:<br>%s<br>%d秒<br>%.2f公里
            </div>
        '''%("blue", "["+",".join(list(map(str, data2[1][0][ii].tolist())))+"]", int(data2[1][2][ii]), float(data1[1][5][ii][0]))
        folium.map.Marker(
            [coordinates[0][0]+0.01, coordinates[0][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_new)        

        folium.Marker(
            location=[coordinates[0][0], coordinates[0][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color=color,    
                fill=True,
                fill_opacity=0.7
            )
        ).add_to(m_one)        

        folium.Marker(
            location=[coordinates[-1][0], coordinates[-1][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color='orange',    
                fill=True,
                fill_opacity=0.7
            )
        ).add_to(m_one)    

        text_html = '''
            <div style="
                font-size: 20px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                %s<br>%s<br>%s<br>
            </div>
        '''%(color, name[:5], name[5:11], name[11:])
        folium.map.Marker(
            [coordinates[0][0]+0.01, coordinates[0][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_one)          

        text_html = '''
                <div style="
                    font-size: 20px;
                    color: %s;
                    white-space: pre-line;     /* 允许自动换行 */
                    width: 200px;">
                    %s(%s)
                </div>
            '''%('orange', "救灾点", destination_name)
        folium.map.Marker(
                [coordinates_list[-1][-1][0]+0.01, coordinates_list[-1][-1][1]],
                icon=folium.DivIcon(
                    #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                    icon_anchor=(0,0),
                    html=text_html
                )
            ).add_to(m_one)               

        print (name, ":", color)

        m_one.fit_bounds(m_one.get_bounds()) 
        m_one.save(map_output_path + "_" + str(ii) + "_style_%d.html" %style)
        ii += 1

    folium.Marker(
            location=[coordinates_list[-1][-1][0], coordinates_list[-1][-1][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color='orange',    
                fill=True,
                fill_opacity=0.7
            )
        ).add_to(m)   
    folium.Marker(
            location=[coordinates_list[-1][-1][0], coordinates_list[-1][-1][1]],
            popup=name,
            icon=folium.Icon(
                icon='circle',      # 圆形标记
                color='orange',    
                fill=True,
                fill_opacity=0.7
            )
        ).add_to(m_new)
    text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                %s(%s)<br>物资需求量:%s<br>调度总时间:%d秒<br>调度物资满足程度:%d%%<br>路线选择:%s
            </div>
        '''%('black', "救灾点", destination_name, "["+",".join(list(map(str,d[0].tolist())))+"]", int(fitness[0]), (1-float(fitness[1]))*100, name_style[style])
    folium.map.Marker(
            [coordinates_list[-1][-1][0]+0.01, coordinates_list[-1][-1][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m)         
    text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                %s(%s)<br>物资需求量: %s
            </div>
        '''%('purple', "救灾点", destination_name, "["+",".join(list(map(str,d[0].tolist())))+"]")
    folium.map.Marker(
            [coordinates_list[-1][-1][0]+0.01, coordinates_list[-1][-1][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_new)        
    text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
                <br><br><br>最快路线:<br>调度总时间%s秒<br>调度物资满足程度:%d%%
            </div>
        '''%('red', int(data2[0][3][0]), (1-float(data2[0][3][1]))*100)
    folium.map.Marker(
            [coordinates_list[-1][-1][0]+0.01, coordinates_list[-1][-1][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_new)        
    text_html = '''
            <div style="
                font-size: 16px;
                color: %s;
                white-space: pre-line;     /* 允许自动换行 */
                width: 200px;">
               <br><br><br><br><br><br>最短路线:<br>调度总时间 %s秒<br>调度物资满足程度:%d%%
            </div>
        '''%('blue', int(data2[1][3][0]), (1-float(data2[1][3][1]))*100)
    folium.map.Marker(
            [coordinates_list[-1][-1][0]+0.01, coordinates_list[-1][-1][1]],
            icon=folium.DivIcon(
                #icon_size=(200, 60),      # 宽度和高度根据文字内容调整
                icon_anchor=(0,0),
                html=text_html
            )
        ).add_to(m_new)                  

    # 自动调整地图视野
    m.fit_bounds(m.get_bounds())
    m_new.fit_bounds(m.get_bounds())

    # 保存地图（支持离线查看）
    m.save(map_output_path + "_style_%d.html" %style)
    m_new.save(map_output_path + "_合并_style_%d.html" %style)

if __name__ == "__main__":
    config = read_json("path_planning/tianditu/config.jsonc")
    map_output_path = config["map_output_path"]
    data_output_path = config["data_output_path"]
    resource_scheduling_path = config["resource_scheduling_path"]
    name_style = {
        0: "最快路线",
        1: "最短路线",
        2: "避开高速",
        3: "步行"
    }    
    data1 = []
    data2 = []
    for style in  [0,1]:                                    #默认0 （0：最快路线，1：最短路线，2：避开高速，3：步行）
        with open(data_output_path+"_style_%d.pkl" %(style), "rb") as haddle:
            data1.append(pickle.load(haddle))
        with open(resource_scheduling_path+"_style%d.pkl" %(style), "rb") as haddle:
            data2.append(pickle.load(haddle))
    for style in  [0,1]:                                    #默认0 （0：最快路线，1：最短路线，2：避开高速，3：步行）            
        print ("style", style)
        with open(data_output_path+"_style_%d.pkl" %(style), "rb") as haddle:
            names, destination_name, origin_list, destination, coordinates_list, datas, style = pickle.load(haddle)
        with open(resource_scheduling_path+"_style%d.pkl" %(style), "rb") as haddle:
            positions, d, t, fitness, style = pickle.load(haddle)
        print ("positions", positions)
        print ("d", d)
        print ("t", t)
        print ("fitness", fitness)
        generate_map(coordinates_list, names, destination_name, style, map_output_path, positions, fitness, d, t, datas, name_style, data1, data2)